﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace WPControla.Client.Services.Podcast
{
    public class PodcastService : IPodcastService
    {
        private WebClient webClient;

        public void GetPodcastData(Uri source)
        {
            webClient = new WebClient();
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted);
            webClient.OpenReadAsync(source);
        }

        void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                EndDownloadRss(e.Result);
            }
        }

        void EndDownloadRss(Stream value)
        {
            XDocument doc = XDocument.Load(value);

            List<Entities.PodcastItem> items = new List<Entities.PodcastItem>();

            var list = doc.Element("rss").Element("channel").Elements("item");
            XNamespace content = XNamespace.Get("http://purl.org/rss/1.0/modules/content/");
            XNamespace itunes = XNamespace.Get("http://www.itunes.com/dtds/podcast-1.0.dtd");
            int count = 0;
            foreach (var item in list)
            {
                items.Add(new Entities.PodcastItem()
                {
                    id = count,
                    Title = item.Element("title").Value,
                    Subtitle = item.Element(itunes.GetName("subtitle")).Value,
                    link = new Uri(item.Element("link").Value),
                    Content = item.Element("description").Value,
                    Audio = new Uri(item.Element("enclosure").Attribute("url").Value, UriKind.Absolute),
                    Authors = item.Element(itunes.GetName("author")).Value
                });
                count++;
            }

            Entities.Podcast rss = new Entities.Podcast()
            {
                Items = new List<Entities.PodcastItem>(items)
            };


            var handler = PodcastDownloadCompleted;
            if (handler != null)
            {
                handler(this, new PodcastDownloadEventArgs(rss));
            }
        }

        public event EventHandler<PodcastDownloadEventArgs> PodcastDownloadCompleted;
    }
}
